<template>
  <div class="params">
     <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 警告框 -->
      <el-alert
        title="注意！只能为第三级分类设置相关参数"
        type="warning"
        show-icon
        :closable="false"
      >
      </el-alert>
      <!-- 选择商品分类 -->
      <el-row class="par-row">
        <el-col>
          <span>选择商品分类：</span>
          <!-- 选择商品分类 -->
          <el-cascader
            v-model="cateListKeys"
            :options="cateList"
            expand-trigger="hover"
            :props="cateListProps"
            clearable
            @change="handleChange">
          </el-cascader>
          <!-- 标签页 -->
           <el-tabs v-model="activeName" @tab-click="handleTabClick">
            <el-tab-pane label="动态参数" name="many">
              <el-button type="primary" size="mini" :disabled="isBtnAbled" @click="addMany">添加参数</el-button>
              <!-- 动态参数表格-->
              <el-table
                :data="manyTableData"
                stripe
                border
              >
                <!-- 展开行 -->
                <el-table-column
                  type="expand" >
                  <!-- tag 标签 -->
                  <template slot-scope="scope">
                    <!-- 循环出来的 tag 标签 -->
                    <el-tag v-for="(item, i) in scope.row.attr_vals" :key="i" closable @close="handleClose(i, scope.row)">
                      {{ item }}
                    </el-tag>
                    <!-- 添加 tag -->
                    <el-input
                      class="input-new-tag"
                      v-show="scope.row.inputVisible"
                      v-model="scope.row.inputValue"
                      ref="saveTagInput"
                      size="small"
                      @keyup.enter.native="handleInputConfirm(scope.row)"
                      @blur="handleInputConfirm(scope.row)"
                    >
                    </el-input>
                    <el-button v-show="!scope.row.inputVisible" class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                  </template>
                </el-table-column>
                <!-- 索引行 -->
                <el-table-column
                  type="index" >
                </el-table-column>
                 <el-table-column
                  prop="attr_name"
                  label="参数名称" >
                </el-table-column>
                <el-table-column
                  label="操作" >
                  <template slot-scope="scope">
                    <el-button type="primary" size="mini" @click="editTable(scope.row)">编辑</el-button>
                    <el-button type="danger" size="mini" @click="removeTable(scope.row.attr_id)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
            <el-tab-pane label="静态属性" name="only">
              <el-button type="primary" size="mini" :disabled="isBtnAbled" @click="addOnly">添加属性</el-button>
              <!-- 静态属性 -->
              <el-table
                :data="onlyTableData"
                stripe
                border
              >
                 <!-- 展开行 -->
                <el-table-column
                  type="expand" >
                  <!-- tag 标签 -->
                  <template slot-scope="scope">
                    <!-- 循环出来的 tag 标签 -->
                    <el-tag v-for="(item, i) in scope.row.attr_vals" :key="i" closable @close="handleClose(i, scope.row)">
                      {{ item }}
                    </el-tag>
                    <!-- 添加 tag -->
                    <el-input
                      class="input-new-tag"
                      v-show="scope.row.inputVisible"
                      v-model="scope.row.inputValue"
                      ref="saveTagInput"
                      size="small"
                      @keyup.enter.native="handleInputConfirm(scope.row)"
                      @blur="handleInputConfirm(scope.row)"
                    >
                    </el-input>
                    <el-button v-show="!scope.row.inputVisible" class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                  </template>
                </el-table-column>
                <!-- 索引行 -->
                <el-table-column
                  type="index" >
                </el-table-column>
                 <el-table-column
                  prop="attr_name"
                  label="参数名称" >
                </el-table-column>
                <el-table-column
                  label="操作" >
                  <template slot-scope="scope">
                    <el-button type="primary" size="mini" @click="editTable(scope.row)">编辑</el-button>
                    <el-button type="danger" size="mini" @click="removeTable(scope.row.attr_id)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
          </el-tabs>
        </el-col>
      </el-row>
    </el-card>
    <!-- 添加弹出框 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClose"
    >
      <!-- 添加参数表单 -->
      <el-form ref="addFormRef" :model="addForm" :rules="addFormRules" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <template slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </template>
    </el-dialog>
    <!-- 修改弹出框 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="addDialogClose"
    >
      <!-- 添加参数表单 -->
      <el-form ref="addFormRef" :model="editForm" :rules="addFormRules" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <template slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 商品分类列表
      cateList: [],
      // 级联选择框双向绑定的数组
      cateListKeys: [],
      // 级联选择框的配置对象
      cateListProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 当前被选中的标签页
      activeName: 'many',
      // 动态参数的属性
      manyTableData: [],
      // 静态参数的属性
      onlyTableData: [],
      // dialog 显示隐藏
      addDialogVisible: false,
      // 表单验证规则
      addFormRules: {
        attr_name: [{ required: true, message: '请输入字符', trigger: 'blur' }]
      },
      // 表单数据
      addForm: {
        attr_name: ''
      },
      editForm: {
        attr_name: ''
      },
      editDialogVisible: false,
      attr_id: ''
    }
  },
  created () {
    this.getCateList()
  },
  computed: {
    // 如果不是三级分类下的情况 button为不可选中‘
    isBtnAbled () {
      if (this.cateListKeys.length !== 3) {
        return true
      }
      return false
    },
    // 当前选中三级分类的id
    cateId () {
      if (this.cateListKeys.length === 3) {
        return this.cateListKeys[this.cateListKeys.length - 1]
      }
      return null
    },
    // dialog对话框title
    titleText () {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    }
  },
  methods: {
    // 获取商品分类
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error('获取商品分类失败！')
      this.cateList = res.data
      // console.log(this.cateList)
    },
    // 级联选择器 当选中节点变化时触发 （回调参数是 选中节点的值）
    handleChange (value) {
      // 如果 cateListKeys 数组的长度等于三 说明是三级分类 否则就不是 就不能显示就把 cateListKeys清空
      if (this.cateListKeys.length !== 3) {
        this.cateListKeys = []
        this.manyTableData = []
        this.onlyTableData = []
        return
      }
      // console.log(this.cateId)
      // 选中了三级分类 发送请求获取分类参数
      this.getParamsData()
    },
    // 获取参数
    async getParamsData () {
      // 选中了三级分类 发送请求获取分类参数
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: this.activeName } })
      if (res.meta.status !== 200) return this.$message.error('获取分类参数失败')
      // 将 attr_vals 变成数组 好进行循环
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        // 控制 input 的显示与隐藏
        item.inputVisible = false
        // 控制 input 的值
        item.inputValue = ''
      })
      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
      console.log(this.manyTableData)
    },
    // tab 被选中时触发
    handleTabClick () {
      // console.log(this.activeName)
      // 获取三级分类
      if (this.cateListKeys.length === 3) {
        this.getParamsData()
      }
    },
    // 点击添加参数
    addMany () {
      this.addDialogVisible = true
    },
    // 点击添加属性
    addOnly () {
      this.addDialogVisible = true
    },
    // 弹出框消失重置表单
    addDialogClose () {
      this.$refs.addFormRef.resetFields()
    },
    // 点击确定按钮
    addParams () {
      // 表单预校验
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        // 表单预校验成功再执行发送请求
        const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`,
          { attr_name: this.addForm.attr_name, attr_sel: this.activeName })
        if (res.meta.status !== 201) return this.$message.error('添加分类失败！')
        this.$message.success('添加分类成功')
        this.getParamsData()
        this.addDialogVisible = false
      })
    },
    // 点击修改
    editTable (scope) {
      this.editDialogVisible = true
      this.editForm.attr_name = scope.attr_name
      this.attr_id = scope.attr_id
    },
    // 点击确定 修改
    editParams () {
      // 表单预校验
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        // 表单预校验成功再执行发送请求
        const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.attr_id}`,
          { attr_name: this.editForm.attr_name, attr_sel: this.activeName })
        if (res.meta.status !== 200) return this.$message.error('编辑分类失败')
        this.$message.success('编辑分类成功')
        this.getParamsData()
        this.editDialogVisible = false
      })
    },
    // 点击删除
    async removeTable (id) {
      const result = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (result !== 'confirm') return this.$message.info('取消了删除')
      const { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/${id}`)
      if (res.meta.status !== 200) return this.$message.error('删除分类失败！')
      this.$message.success('删除成功')
      this.getParamsData()
    },
    async saveAttrVals (row) {
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' ')
        })
      if (res.meta.status !== 200) return this.$message.error('修改参数选项失败！')
      this.$message.success('修改参数选项成功')
    },
    // 键盘抬起 enter 失去焦点都会执行 添加 tag
    handleInputConfirm (row) {
      // console.log('ok')
      // 去除 inputValue的空格 之后空格是否等于 0
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        // eslint-disable-next-line
        return
      }
      // 如果没有 return 则证明输入了内容 需要做后续处理
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      // 发送请求 保存到数据库
      this.saveAttrVals(row)
    },
    // 点击 按钮 展示 input
    showInput (row) {
      row.inputVisible = true
      // $nextTick的作用：当页面上元素重新渲染之后，
      // 才会指定回调函数中的代码
      this.$nextTick(_ => {
        // 自动获取焦点
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 删除 tag
    handleClose (i, row) {
      row.attr_vals.splice(i, 1)
      // 发送请求 保存到数据库
      this.saveAttrVals(row)
    }
  }
}
</script>

<style lang="less" scoped>
.par-row {
  margin-top: 20px;
}
.el-tag {
  margin: 5px;
}
.input-new-tag {
  width: 120px;
}
</style>
